from langchain.tools import tool
from home.search_utils import SearchEngine
from utils.synonym import expand_synonyms
import re

search_engine = SearchEngine()

def parse_query(query: str):
    """
    从query字符串中提取关键词、分类、排序、筛选等信息。
    例如：'瑜伽训练 分类:posts 排序:time 筛选:user.username=张三'
    """
    keyword = query
    category = None
    sort = 'relevance'
    filters = {}
    # 分类
    m = re.search(r'分类[:：](\w+)', query)
    if m:
        category = m.group(1)
    # 排序
    m = re.search(r'排序[:：](\w+)', query)
    if m:
        sort = m.group(1)
    # 筛选
    m = re.search(r'筛选[:：]([\w\.]+)=([\w\u4e00-\u9fa5]+)', query)
    if m:
        filters[m.group(1)] = m.group(2)
    # 关键词（去掉所有指令）
    keyword = re.sub(r'(分类[:：]\w+)|(排序[:：]\w+)|(筛选[:：][\w\.]+=([\w\u4e00-\u9fa5]+))', '', query).strip()
    return keyword, category, sort, filters

@tool("synonym_expand_tool")
def synonym_expand_tool(query: str) -> list:
    """对输入文本进行同义词扩展"""
    return expand_synonyms(query)

@tool("es_search_tool")
def es_search_tool(query: str) -> dict:
    """用ES搜索，query格式如：'关键词 分类:posts 排序:time 筛选:user.username=张三'"""
    keyword, category, sort, filters = parse_query(query)
    return search_engine.es_search(keyword, category, sort, filters)

@tool("mysql_search_tool")
def mysql_search_tool(query: str) -> dict:
    """用MySQL模糊搜索，query格式如：'关键词 分类:posts 排序:time 筛选:user.username=张三'"""
    keyword, category, sort, filters = parse_query(query)
    return search_engine.mysql_search(keyword, category, sort, filters) 